package com.symaster.common.connect.tcp;

import com.alibaba.fastjson.JSONObject;
import com.symaster.common.connect.util.ClientIO;
import com.symaster.common.util.IOUtil;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author yinmiao
 * @version 2022-05-03 15:37
 */
public class TcpElementW implements Closeable {

    private final String ip;
    private final int port;
    private Socket socket;
    private OutputStream os;
    private InputStream is;

    public TcpElementW(String ip, int port) throws IOException {
        this.ip = ip;
        this.port = port;
        init();
    }

    private void init() throws IOException {
        socket = new Socket(ip, port);
        socket.setReceiveBufferSize(102400);
        os = socket.getOutputStream();
        is = socket.getInputStream();
    }

    public void send(String message) throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", message);
        jsonObject.put("type", "notResult");
        ClientIO.writeStr(os, jsonObject.toJSONString());
    }

    public String sendAndWait(String message) throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", message);
        jsonObject.put("type", "result");
        ClientIO.writeStr(os, jsonObject.toJSONString());
        String result = ClientIO.getString(is);
        if ("$$$NULL$$$".equals(result)) {
            return null;
        }
        return result;
    }

    @Override
    public void close() throws IOException {
        IOUtil.close(socket, os, is);
    }
}
